import { Component, Input, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesModalRef } from '@shared/apes/modal';
import { deepClone } from '../../utils/utils';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { UserAuthService } from '@core/services/user-auth.service';


@Component({
  selector: 'drawer-inquiry',
  templateUrl: './drawer-inquiry.component.html',
})
export class DrawerInquiryComponent implements OnInit {
  // form 定义相关
  // form = new FormGroup({ textInfo: new FormControl('') });
  model: any = {};
  options: any;
  resultsData: any = [];

  @Input() api: any;
  @Input() data: any;
  id: string;                               // 方案号

  inquiryFilterData: any[] = [];
  inquiryData: any[] = [];
  inquiryShowData: any[] = [];
  inquiryLoading: boolean = false;
  showHidden: boolean = false;

  filterField: any = [
    { type: 'PJMC', name: '配件' }, // 配件
    { type: 'ZDMC', name: '送达站点' }, // 送达站点
    { type: 'PZMC', name: '品质' }, // 品质
  ];
  showField: any[] = [];

  inventoryData: any[] = [];
  inventoryLoading: boolean = false;
  enquiryData: any[] = [];

  pagination: any = {
    total: 0,
    pageSize: 5,
    currentPage: 0,
  };
  pageIndex: any = 0;


  constructor(private apiService: ApiService,
              protected userService: UserAuthService,
              protected expressionService: ExpressionService,
              public modal: ApesModalRef) {

  }

  ngOnInit() {
    this.getData();
    this.getInventoryData(this.pageIndex);
  }

  getData() {
    this.id = this.data.id;
    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';
    const data = { node: this.data.node, ...this.data, platform: platform };
    this.inquiryLoading = true;
    this.apiService.post(this.api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.inquiryFilterData = body.inquiryPool.item;
          this.inquiryData = body.inquiryPool.item;
          this.inquiryShowData = deepClone(this.inquiryData);
          this.filterCondition();
          if (this.data.hasOwnProperty('node')) {
            this.checkFiltrationData();
          }
          this.enquiryData = body.requireTrack;
        }
        this.inquiryLoading = false;
      });

  }

  getInventoryData(pageIndex) {
    let api = 'scm.externalInquiry.getProductStockInfo';
    let node = this.data.node;
    const data =
      {
        'condition': [
          {
            'field': 'categoryTemp',
            'value': node['category']['id'],
            'operator': 'LIKE',
          },
          {
            'field': 'relationType',
            'value': 'no_auto',
            'operator': 'EQ',
          },
          {
            'field': 'searchContent',
            'value': {
              'partsTagId': node['category']['id'],
              'partsTagName': node['category']['name'],
            },
            'operator': 'EQ',
          },
        ],
        'sourceBusinessKey': this.data['sourceBusinessKey'],
        'sourceBusinessType': this.data['sourceBusinessType'],
        'size': this.pagination.pageSize,
        'page': pageIndex,
      };
    this.inventoryLoading = true;
    this.inventoryData = [];
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.inventoryData = body.content;
          this.pagination.total = body.total;
          this.pagination.currentPage = body.page + 1;
          if (this.inventoryData.length != 0) {
            let sApi = 'scm.externalInquiry.getProductStockInfoPrice';
            let sourceBusinessKey = this.data['sourceBusinessKey'];
            let sourceBusinessType = this.data['sourceBusinessType'];
            this.inventoryData.forEach((res) => {
              let reqData = {
                'productId': res['id'],
                'sourceBusinessKey': sourceBusinessKey,
                'sourceBusinessType': sourceBusinessType,
              };
              this.apiService.post(sApi, { 'body': JSON.stringify(reqData) }).subscribe((sBody) => {
                // console.log(sBody);
                res.referTax = sBody['referTax'];
              });

            });
          }
        }
        this.inventoryLoading = false;
      });
  }

  filterCondition() {

    this.filterField.forEach((field) => {
      field.data = [];
      field.data = this.filtrationData(field.type);
    });
  }

  filtrationData(type) {
    let showData = [];
    let list = deepClone(this.inquiryFilterData);
    let node = deepClone(this.data.node);
    let showField = deepClone(this.showField);
    list.forEach((data) => {
      data.item.forEach((res) => {
        let check = true;
        showData.forEach((sd) => {
          if (sd[type] == res[type]) {
            check = false;
          }
        });
        if (check) {
          let checked = true;
          if (node && type == 'PJMC') {
            if (res[type] == node['category']['name']) {
              checked = true;
              this.showField.push(...data.item);
            } else {
              checked = false;
            }
            showData.push({ [type]: res[type], checked: checked });
          } else if (type != 'PJMC') {
            let showChecked = false;
            showField.forEach((field) => {
              if (res[type] == field[type]) {
                showChecked = true;
              }
            });
            if (showChecked) {
              showData.push({ [type]: res[type], checked: checked });
            }
          }
        }
      });
    });
    return showData;
  }

  checkFiltrationData() {
    let show = true;
    let list = deepClone(this.inquiryData);
    list.forEach((data) => {
      data.item = data.item.filter((item) => {
        return this.filter(item);
      });
      if (data.item.length != 0) {
        show = false;
      }
    });
    this.inquiryShowData = list;
    this.showInquiry = show;
  }

  showInquiry: boolean = false;

  filter(filterData) {
    let check = true;
    this.filterField.forEach((field) => {
      let type = field.type;
      field.data.forEach((data) => {
        if (data[type] == filterData[type] && check != false) {
          check = data.checked;
        }
      });
    });
    return check;
  }

  getValueFormatter(data: any) {
    let expression = 'data.MESSAGE +  \'\\r\\n\' + data.ZXRQ_SJ';
    return this.expressionService.evaluate(expression, {
      data: data,
    });
  }

  showStock(data) {
    if (data.hasOwnProperty('area') || data.hasOwnProperty('general')) return;
    let api = 'fn.service.findStockByProduct';
    let setData = {
      condition: data,
      conditionModel: this.data,
    };
    this.apiService.post(api, setData).subscribe((body) => {
      console.log(body);
      if (body) {
        data['area'] = body['area'];
        data['general'] = body['general'];
      }
    });
  }

  getStockAmountTooltipFormatter(data) {
    let show =
      '门店实际库存：' + data.usableQTY + '<br/>' +
      '服务单确认未领料库存：-' + data.frozenQTY + '<br/>' +
      '转储收货在途：' + data.transferReceiveQty + '<br/>' +
      '订货在途：' + data.purchasingWayQty + '<br/>' +
      '转入制单数：' + data.transferInBillingQty + '<br/>' +
      '要货数：' + data.requireBillingQty;
    return show;
  }

  getStockTooltipFormatter(data, type) {
    let show = '加载中...';
    if (data.hasOwnProperty(type)) {
      let text = '';
      data[type].forEach((res) => {
        if (res.hasOwnProperty('companyId')) {
          text += '[' + res.companyId + ']' + res.companyName + '<br/>'
            + '- 库存：' + res.stock + '<br/>';
          // + '- 参考成本：' + res.referTax + '<br/>';
        } else if (res.hasOwnProperty('stockType')) {
          text += '- ' + res.stockType + '：' + res.stock + '<br/>';
        }
      });
      show = text;
    }
    return show;
  }

  pageIndexChange($event) {
    let index = $event - 1;
    this.pagination.currentPage = $event;
    this.pageIndex = index;
    this.getInventoryData(this.pageIndex);
  }

  destroyModal(): void {
    this.modal.destroy(this.resultsData);
  }

  openShowHidden() {
    this.showHidden = !this.showHidden;
  }

  resetCondition() {
    this.filterField.forEach((field) => {
      if (field.type != 'PJMC') {
        field.data.forEach((data) => {
          data.checked = true;
        });
      }
    });
    this.checkFiltrationData();
    this.showInquiry = false;
  }

}
